<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!--提示区域  -->
      <el-alert show-icon title="消息提示的文案" type="info" :closable="false" center></el-alert>
      <!-- 步骤条区域 -->
      <el-steps :space="200" :active="activeIndex-0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tab栏 -->
      <el-form
        :model="addForm"
        :rules="addRules"
        ref="addRuleForm"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          v-model="activeIndex"
          :tab-position="'left'"
          :before-leave="activeLeave"
          @tab-click="tabClisck"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop>
              <!-- 级联选择器 -->
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="cascaderProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 渲染表单的item项 -->
            <el-form-item :label="item.attr_name" v-for="item in manyList" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals" border>
                <el-checkbox border :label="cb" v-for="(cb,i) in item.attr_vals" :key="i"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyList" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <!-- 图片上传功能 -->
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              class="upload-demo"
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture" :headers="headerObj" :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button type="primary" class="addBtn" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览弹出框 -->
    <el-dialog
  title="预览图片"
  :visible.sync="previewVisible"
  width="50%">
  <img :src="previewPath" alt="">
</el-dialog>
  </div>
</template>
<script>
import _ from 'lodash'
import { async } from 'q';
export default {
  data() {
    return {
      activeIndex: "0",
      addForm: {
        goods_name: "",
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_cat: [],
        pics:[],
        // 介绍
        goods_introduce:'',
        attrs:[]
      },
      addRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" }
        ],
        goods_price: [
          { required: true, message: "请输入商品名称", trigger: "blur" }
        ],
        goods_number: [
          { required: true, message: "请输入商品名称", trigger: "blur" }
        ],
        goods_weight: [
          { required: true, message: "请输入商品名称", trigger: "blur" }
        ]
      },
      //   商品分类列表
      cateList: [],
      cascaderProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        expandTrigger: "hover"
      },
      //   动态参数数据
      manyList: [],
      //静态参数数据
      onlyList: [],
    //   图片的url上传的地址
      uploadURL:'http://127.0.0.1:8888/api/private/v1/upload',
      // 图片请求头，携带token
    headerObj:{
        Authorization:window.sessionStorage.getItem('token')
    },
    // 图片预览
    previewPath:'',
    previewVisible:false
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) {
        return this.$message.error("获取商品数据分类失败");
      }
      this.cateList = res.data;
      //   console.log(this.cateList);
      //   this.getCateList();
    },
    handleChange() {
      console.log(this.addForm.goods_cat);
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = [];
      }
    },
    activeLeave(activeName, oldActiveName) {
      if (oldActiveName === "0" && this.addForm.goods_cat.length !== 3) {
        this.$message.error("请先选择商品分类");
        return false;
      }
    },
    // 动态参数面板
    async tabClisck() {
      if (this.activeIndex === "1") {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: "many" }
          }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("获取动态参数失败");
        }
        console.log(res.data);

        // 渲染页面前将字符串转为数组类型
        res.data.forEach(item => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(" ");
        });
        this.manyList = res.data;
        // name='2'时的静态属性
      } else if (this.activeIndex === "2") {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: "only" }
          }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("获取静态参数失败");
        }
        console.log(res.data);
        this.onlyList = res.data;
      }
    },
    // 图片预览功能
    handlePreview(file){
      console.log(file);
      // 图片预览的真实路径
      this.previewPath=file.response.data.url
      this.previewVisible=true
    },
    //图片移除功能 
    handleRemove(file){
      console.log(file);
      // 获取删除图片的临时路径
      const filePath=file.response.data.tmp_path
      // 图片对应的索引值
      const i=this.addForm.pics.findIndex(x=>x.pic===filePath)
      // 使用splice(i,1)删除索引，一个
      this.addForm.pics.splice(i,1)
    },
    // 图片上传的临时路径
    handleSuccess(response){
        console.log(response);
        // 拼接一个图片路径对象
        const picsInfo={pic:response.data.tmp_path}
        // 将图片信息对象，push到数组中
        this.addForm.pics.push(picsInfo)
        console.log(this.addForm);
        
    },
    // 添加商品
    add(){
      this.$refs.addRuleForm.validate(async valid=>{
        if(!valid) return this.$message.error('请填写必要的表单项')
        // 进行addFrom深拷贝 loash 
        // 此方法也可进行深拷贝，先将原数组转换为字符串
        // const from =JSON.parse(JSON.stringify(this.addForm))
        // console.log(from===this.addForm);//返回false也就是两个值不等
        
        const from=_.cloneDeep(this.addForm)
        from.goods_cat=from.goods_cat.join(',')
        // 处理动态参数
        this.manyList.forEach(item=>{
          const newInfo={
            attr_id:item.attr_id,
            attr_value:item.attr_vals.join(' ')
          }
          this.addForm.attrs.push(newInfo)
          console.log(1);
          
        })
        // 处理静态参数
        this.onlyList.forEach(item=>{
          const newInfo={
            attr_id:item.attr_id,
            attr_value:item.attr_vals
          }
          this.addForm.attrs.push(newInfo)
        })
        from.attrs=this.addForm.attrs
        // 发起添加商品请求
        const {data:res}=await this.$http.post('goods',from)
        if(res.meta.status!==201){
          return this.$message.error('添加商品失败')
        }
        this.$message.success('添加商品成功')
        this.$router.push('/goods')
      })
    }
  },
  computed: {
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2];
      }
      return null;
    }
  }
};
</script>

<style lang="less" scope>
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
img {
  width: 100%;
}
.addBtn {
  margin-top: 15px!important;
}
</style>